package com.wzy.chain_responsibility.demo1;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: wzy
 * @Date: 2022/10/08/19:24
 * @Description:
 */
@Component
public class OrderHandleChainService implements ApplicationContextAware {

    private List<OrderHandleIntercept> handleList = new ArrayList<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        // 获取指定类的接口，并按照sort进行排序，放入List中
        Map<String, OrderHandleIntercept> serviceMap = applicationContext.getBeansOfType(OrderHandleIntercept.class);
        handleList = serviceMap.values().stream().sorted(Comparator.comparingInt(OrderHandleIntercept::sort)).collect(Collectors.toList());
    }

    public OrderContext execute(OrderContext context) {
        for (OrderHandleIntercept orderHandleIntercept : handleList) {
            orderHandleIntercept.handle(context);
        }
        return context;
    }
}
